<template>
  <div class="articleList" ref="article-list">
    <van-pull-refresh v-model="inRefreshLoading" @refresh="onRefresh" :success-text="RefreshSuccessText" success-duration="1500">
      <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
        <article-item v-for="(article,index) in articles" :key="index" :article="article"></article-item>
    </van-list>
    </van-pull-refresh>
  </div>
</template>
<script>
import { getArticles } from '@/api/article'
import articleItem from '@/components/article-item'
import { debounce } from 'lodash'
  export default {
    components:{
      articleItem
    },
    props: {
      channel  : {
        type: Object,
        required: true
      }
    },
    data() {
      return {
        articles: [],
        loading: false,
        finished: false,  
        timestamp:null, //获取下一页数据的事件戳
        inRefreshLoading:false,  //lodding
        RefreshSuccessText:'', //success文本
        scrollTop: 0 //列表距离顶部
      }
    },
    mounted(){
      const articleList = this.$refs['article-list']
      articleList.onscroll =debounce(() =>{
        this.scrollTop =articleList.scrollTop
      },50)
    },
    activated(){
      // console.log('从缓存中被激活');
      this.$refs['article-list'].scrollTop = this.scrollTop
    },
    deactivated(){
      // console.log('失去活动状态');
    },
    methods: {
      async onLoad() {
        const res = await getArticles({
          channel_id:this.channel.id,
          timestamp:this.timestamp || Date.now(),
          with_top:1
        })
        // console.log(res.data);
        //吧数据放到articles数组
        let {results} = res.data.data
        this.articles.push(...results)

        this.loading =false

        if( results.length ){
          this.timestamp = res.data.data.pre_timestamp
        }else{
          this.finshed=true
        }  
      },
      async onRefresh(){
        const res = await getArticles({
          channel_id:this.channel.id,
          timestamp:Date.now(),
          with_top:1
        })
        //将数据添加到数组顶部（上啦刷新
        let {results} = res.data.data
        this.articles.unshift(...results)
        this.inRefreshLoading = false
        this.RefreshSuccessText=`跟新了${results.length}条数据`
      }
    }
  }
</script>
<style lang="scss" scoped>
.articleList {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 50px;
  top: 90px;
  overflow-y: auto;
}
</style>